package com.wutu.nbyjk8.service.impl;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class EnergyForwarder {

    private final RestTemplate restTemplate;

    public EnergyForwarder(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 通用转发方法
     *
     * @param restType      请求类型："GET" 或 "POST"
     * @param restUrl       目标接口URL
     * @param restBody      POST时请求体对象，GET时可为null
     * @param authorization 可选的Authorization header内容，为null时不加
     * @return ResponseEntity<String>
     */
    public ResponseEntity<String> forwardRequest(String restType, String restUrl, Object restBody, String authorization) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (authorization != null && !authorization.isEmpty()) {
            //headers.set("Authorization", authorization);
            headers.setBearerAuth(authorization);
        }

        HttpEntity<?> entity = restType.equalsIgnoreCase("POST") ?
                new HttpEntity<>(restBody, headers) :
                new HttpEntity<>(headers);

        if (restType.equalsIgnoreCase("GET")) {
            return restTemplate.exchange(restUrl, HttpMethod.GET, entity, String.class);
        } else if (restType.equalsIgnoreCase("POST")) {
            return restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class);
        } else {
            throw new IllegalArgumentException("Unsupported restType: " + restType);
        }
    }
}

